package com.streamer.app.fragment

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Typeface
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.media.projection.MediaProjectionManager
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import android.widget.EditText
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.SeekBar
import android.widget.TextView
import android.widget.Toast
import android.graphics.Canvas
import android.graphics.Paint
import androidx.activity.result.contract.ActivityResultContracts
import android.graphics.Color
import androidx.appcompat.widget.SwitchCompat
import androidx.core.view.marginTop
import androidx.fragment.app.viewModels
import androidx.fragment.app.activityViewModels
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import com.alivc.live.annotations.AlivcLiveMode
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.CustomTarget
import com.bumptech.glide.request.transition.Transition
import com.alivc.live.pusher.AlivcLivePusher
import com.alivc.live.pusher.AlivcLivePushInfoListener
import com.alivc.live.pusher.AlivcLivePushStatsInfo
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.streamer.app.CouponActivity
import com.streamer.app.GiftEffectActivity
import com.streamer.app.LotteryActivity
import com.streamer.app.R
import com.streamer.app.ThreePaneLiveActivity
import com.streamer.app.adapter.BottomButtonAdapter
import com.streamer.app.adapter.ProductListAdapter
import com.streamer.app.adapter.ProductPagerAdapter
import com.streamer.app.bean.BottomButtonItem
import com.streamer.app.bean.LiveBean
import com.streamer.app.databinding.FragmentWhiteboardBinding
import com.streamer.app.fragment.BaseFragment
import com.streamer.app.model.MyViewModel
import com.streamer.app.utils.BottomSheetUtils
import com.streamer.app.utils.BottomSheetUtils.showLocalPlayDialog
import com.streamer.app.utils.ToastUtil
import com.streamer.app.utils.Utils
import com.streamer.app.widget.WhiteboardDrawingView

class WhiteboardFragment : BaseFragment<FragmentWhiteboardBinding>() {

    private var mliveData: LiveBean? = null
    private var bottomSheetDialog: BottomSheetDialog? = null
    private var coursewarePages: MutableList<Any> =
        mutableListOf() // only courseware pages; page 0 is whiteboard
    private var viewPager: ViewPager2? = null
    private var pageInfoView: TextView? = null
    private var btnPrev: TextView? = null
    private var btnNext: TextView? = null
    private var currentPageIndex: Int = 0 // 0 = whiteboard, >0 = courseware index + 1

    // 白板工具按钮
    private var btnMove: ImageView? = null
    private var btnPen: ImageView? = null
    private var btnEraser: ImageView? = null
    private var btnLine: ImageView? = null
    private var btnText: ImageView? = null
    private var btnShape: ImageView? = null
    private var btnFill: ImageView? = null
    private lateinit var tabOnSale: TextView
    private lateinit var tabOffShelf: TextView
    private var mIsMute = true
    private var mIsCamera = true

    // 当前选中的工具
    private var currentSelectedTool: ImageView? = null
    val mAlivcLivePusher = AlivcLivePusher()

    // 录屏推流相关
    private var isScreenStreaming = false
    private var mediaProjectionResultCode: Int = -1
    private var mediaProjectionData: Intent? = null

    // 点赞相关
    private var consecutiveLikeClicks = 0
    private var likeHandler = Handler()
    private val LIKE_DELAY = 1000L // 1秒延迟
    private var lastUseState: Int? = null
    private var isRefreshingLiveInfo = false

    private var productListDialog: BottomSheetDialog? = null
    private var searchDialog: BottomSheetDialog? = null
    private val viewModel: MyViewModel by activityViewModels()

    override fun initView() {
//        // 使用普通推流模式
        mAlivcLivePushConfig.livePushMode = AlivcLiveMode.AlivcLiveBasicMode

        // 初始化推流器
        mAlivcLivePusher.init(requireActivity(), mAlivcLivePushConfig)

        // 设置推流监听器
        setupPushListener()

        // 初始化视图
        initViews()
        // 白板自身需要直播信息用于渲染（如课程、按钮状态等），单独拉取一次数据即可，不会开启相机
        viewModel.message.observe(viewLifecycleOwner) {
            tabOnSale.text = "售卖中 ($it)"
        }
        viewModel.message2.observe(viewLifecycleOwner) {
            tabOffShelf.text = "已下架 ($it)"
        }
    }

    private fun initViews() {
        // 绑定分页控件
        viewPager = _binding.vpPages
        pageInfoView = _binding.tvPageInfo
        btnPrev = _binding.btnPrevPage
        btnNext = _binding.btnNextPage

        // 初始化页面：仅课程页放入ViewPager，白板为第0页独立展示
        coursewarePages.clear()
        currentPageIndex = 0
        setupPager(adapterRebuild = true)
        setupPagingControls()

        _binding.btnMore.setOnClickListener {
            showBottomSheet()
        }
        _binding.btnCamera.setOnClickListener {
            mIsCamera = !mIsCamera
            (requireActivity() as? ThreePaneLiveActivity)?.openCamera(mIsCamera)
        }
        viewMode.LiveInfoLV.observe(viewLifecycleOwner) {
            Log.d("xxxx","LiveInfoLV========>${it}")
            mliveData = it
            val newState = it?.useState
            if (newState == lastUseState) return@observe
            lastUseState = newState
            viewMode.getCoursewareInfo(mliveData?.id.toString())
            _binding.drawingView.post {
                if (_binding.drawingView.width > 0 && _binding.drawingView.height > 0) {
                    startRecord(_binding.drawingView,mliveData?.pushLive3PUrl?.replace("artc://","rtmp://"))
                } else {
                    _binding.drawingView.postDelayed({
                        if (_binding.drawingView.width > 0 && _binding.drawingView.height > 0) {
                            startRecord(_binding.drawingView, mliveData?.pushLive3PUrl?.replace("artc://","rtmp://"))
                        }
                    }, 500)
                }
            }
            when (newState) {
                0 -> {
                    _binding.btnStartLive.visibility = View.VISIBLE

                }

                1 -> {
                    _binding.btnStartLive.visibility = View.GONE
                    //直播中
                    startScreenCapturePush()

                }

                2 -> {
//                    _binding.btnStartLive.visibility = View.GONE
                    (requireActivity() as? ThreePaneLiveActivity)?.endLive()
                }


            }

        }
        _binding.btnStartLive.setOnClickListener {
            viewMode.startLive()
            startScreenCapturePush()
            _binding.btnStartLive.visibility = View.GONE
            viewMode.getLiveInfo()
            // 延迟启动录制，确保视图已完成布局

        }
        viewMode.liveStateLv.observe(requireActivity(), {
            if (it != null) {
                // 由白板触发 Activity 拉取并按需开播
                (requireActivity() as? ThreePaneLiveActivity)?.triggerStartFromWhiteboard()
                _binding.btnStartLive.visibility = View.GONE
            }
        })

        // Bind right toolbar buttons to drawing_view
        val drawingView = _binding.drawingView
        btnMove = _binding.btnMove
        btnPen = _binding.btnPen
        btnEraser = _binding.btnEraser
        btnLine = _binding.btnLine
        btnText = _binding.btnText
        btnShape = _binding.btnShape
        btnFill = _binding.btnFill

        // 设置默认选中移动工具
        setSelectedTool(btnMove)

        btnMove?.setOnClickListener {
            drawingView.setMode(WhiteboardDrawingView.ToolMode.PAN)
            setSelectedTool(btnMove)
        }
        btnPen?.setOnClickListener {
            drawingView.setMode(WhiteboardDrawingView.ToolMode.DRAW)
            // 调用下方定义的方法
            showBrushPicker(this@WhiteboardFragment, drawingView, false,true)
            setSelectedTool(btnPen)
        }
        btnEraser?.setOnClickListener {
            drawingView.setMode(WhiteboardDrawingView.ToolMode.DRAW)
            // 调用下方定义的方法
            showBrushPicker(this@WhiteboardFragment, drawingView, true,true)
            setSelectedTool(btnEraser)
        }
        btnLine?.setOnClickListener {
            drawingView.setMode(WhiteboardDrawingView.ToolMode.LINE)
            setSelectedTool(btnLine)
        }
        btnText?.setOnClickListener {
            drawingView.setMode(WhiteboardDrawingView.ToolMode.TEXT)
            setSelectedTool(btnText)
        }
        btnShape?.setOnClickListener {
            drawingView.setMode(WhiteboardDrawingView.ToolMode.ERASE_WHITE_CIRCLE)
            setSelectedTool(btnShape)
        }

        _binding.btnShop.setOnClickListener {

            showProductListDialog()
        }
        btnFill?.setOnClickListener {
            drawingView.clearAll()
            // 填充工具不需要选中状态，因为它是操作而不是模式
        }



        // 点赞按钮动画
        _binding.ivRecord.setOnClickListener {
            Utils.playLikeAnimation(_binding.ivRecord)
            consecutiveLikeClicks++

            // 取消之前的延迟任务
            likeHandler.removeCallbacksAndMessages(null)

            // 设置1秒后发送点赞请求
            likeHandler.postDelayed({
                if (consecutiveLikeClicks > 0) {
                    viewMode.like(consecutiveLikeClicks.toString())
                    consecutiveLikeClicks = 0 // 重置计数器
                }
            }, LIKE_DELAY)
        }
        _binding.btnMic.setOnClickListener {
            if (mIsMute) {
                // 当前是静音状态，点击后取消静音
                mIsMute = false
                (requireActivity() as? ThreePaneLiveActivity)?.setLiveMute(false)
                _binding.btnMic.setBackgroundResource(R.drawable.mic_icon)
            } else {
                // 当前不是静音状态，点击后开启静音
                mIsMute = true
                (requireActivity() as? ThreePaneLiveActivity)?.setLiveMute(true)
                _binding.btnMic.setBackgroundResource(R.drawable.mic_off_icon)
            }
        }
        viewMode.CoursewareListLV.observe(requireActivity()) { coursewareData ->
            coursewareData?.let {
                coursewareList.clear()
                coursewareList.addAll(it)
                Log.d("WhiteboardFragment", "课件列表数据更新，共 ${it.size} 个文件")
            }
        }


        drawingView.setOnRequestText { x, y ->
            val input = EditText(requireContext())
            input.hint = "输入文字"
            MaterialAlertDialogBuilder(requireContext()).setTitle("添加文字").setView(input)
                .setPositiveButton("确定") { d, _ ->
                    val t = input.text?.toString()?.trim()
                    if (!t.isNullOrEmpty()) drawingView.addTextAt(t, x, y)
                    d.dismiss()
                }.setNegativeButton("取消") { d, _ -> d.dismiss() }.show()
        }

        viewMode.CoursewareInfoLV.observe(requireActivity()) { list ->
            when {
                list.isNullOrEmpty() -> {
                    // 处理空数据情况
                    _binding.bottomPageControls.visibility = View.GONE
                    coursewarePages.clear()
                    currentPageIndex = 0
                    // 重置白板背景与笔迹
                    _binding.drawingView.background = null
                    _binding.drawingView.clearAll()
                    updatePageInfo(1, 1)
                }

                list[0].conversionContent.isEmpty() -> {
                    // 处理conversionContent为空的情况
                    _binding.bottomPageControls.visibility = View.GONE
                    coursewarePages.clear()
                    currentPageIndex = 0
                    // 重置白板背景与笔迹
                    _binding.drawingView.background = null
                    _binding.drawingView.clearAll()
                    updatePageInfo(1, 1)
                }

                else -> {
//                    val firstItem = list[0]
//                    val contents = firstItem.conversionContent
//
//                    _binding.bottomPageControls.visibility = View.VISIBLE
//                    coursewarePages.clear()
//                    coursewarePages.addAll(contents)
//                    currentPageIndex = 0
//                    setupPager(adapterRebuild = true)
//                    showPage(0)
                }
            }
        }


    }

    private fun refreshProductCountsInDialog() {
        // 延迟一下确保数据更新完成
        viewMode.getOnSaleProductCount(mliveData?.id.toString() ?: "")
        viewMode.getOffShelfProductCount(mliveData?.id.toString() ?: "")
    }


    private fun showProductListDialog() {
        refreshProductCountsInDialog()
        if (productListDialog == null) {
            productListDialog = BottomSheetDialog(requireActivity())


            val productListView = layoutInflater.inflate(R.layout.bottom_sheet_product_list, null)

            // 设置商品弹出框的高度
            val displayMetrics = resources.displayMetrics
            val screenHeight = displayMetrics.heightPixels
            val dialogHeight = (screenHeight * 0.7).toInt() // 设置为屏幕高度的70%

            val layoutParams = ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, dialogHeight
            )
            productListView.layoutParams = layoutParams

            productListDialog?.setContentView(productListView)

            // 设置弹窗属性
            productListDialog?.setCancelable(true)
            productListDialog?.setCanceledOnTouchOutside(true)

            // 设置商品列表弹窗的控件监听
            setupProductListListeners(productListView)
        }

        productListDialog?.show()
    }

    private fun setupProductListListeners(view: View) {
        // ViewPager设置
        val viewPager = view.findViewById<ViewPager2>(R.id.view_pager)
        val pagerAdapter = ProductPagerAdapter(requireActivity(), mliveData?.id.toString() ?: "")
        viewPager.adapter = pagerAdapter

        // 标签页切换
        tabOnSale = view.findViewById<TextView>(R.id.tab_on_sale)
        tabOffShelf = view.findViewById<TextView>(R.id.tab_off_shelf)

        // 指示器
        val indicator1 = view.findViewById<View>(R.id.indicator_1)
        val indicator2 = view.findViewById<View>(R.id.indicator_2)


        // 显示售卖中商品
        fun showOnSaleProducts() {
            tabOnSale.setTextColor(requireActivity().getColor(R.color.black))
            tabOnSale.textSize = 16f
            tabOnSale.setTypeface(null, Typeface.BOLD)

            tabOffShelf.setTextColor(requireActivity().getColor(R.color.gray))
            tabOffShelf.textSize = 16f
            tabOffShelf.setTypeface(null, Typeface.NORMAL)

            viewPager.currentItem = 0

            // 更新指示器
            indicator1.setBackgroundResource(R.drawable.indicator_active)
            indicator2.setBackgroundResource(R.drawable.indicator_inactive)
        }

        // 显示已下架商品
        fun showOffShelfProducts() {
            tabOffShelf.setTextColor(requireActivity().getColor(R.color.blue_primary))
            tabOffShelf.textSize = 16f
            tabOffShelf.setTypeface(null, Typeface.BOLD)

            tabOnSale.setTextColor(requireActivity().getColor(R.color.gray))
            tabOnSale.textSize = 16f
            tabOnSale.setTypeface(null, Typeface.NORMAL)

            viewPager.currentItem = 1

            // 更新指示器
            indicator1.setBackgroundResource(R.drawable.indicator_inactive)
            indicator2.setBackgroundResource(R.drawable.indicator_active)
        }

        // 设置标签页点击事件
        tabOnSale.setOnClickListener {
            showOnSaleProducts()
        }

        tabOffShelf.setOnClickListener {
            showOffShelfProducts()
        }

        // ViewPager页面切换监听
        viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                when (position) {
                    0 -> showOnSaleProducts()
                    1 -> showOffShelfProducts()
                }
            }
        })

        // 获取商品数量并更新标签页
        updateProductCounts()

        // 默认显示售卖中商品
        showOnSaleProducts()

        // 搜索按钮点击事件
        val searchLayout = view.findViewById<LinearLayout>(R.id.search_layout)
        val switchShoppingCart = view.findViewById<SwitchCompat>(R.id.switch_shopping_cart)
        searchLayout.setOnClickListener {
            showSearchDialog()
        }
        //开关调用小黄车接口
        switchShoppingCart.setOnClickListener {
            viewMode.closeOpenYellowCar()
        }
        if (mliveData?.isYellowCarEnabled == true) {
            switchShoppingCart.isChecked = false
            viewMode.closeOpenYellowCar()

        } else {
            switchShoppingCart.isChecked = true
            viewMode.closeOpenYellowCar()


        }
        // 设置点击外部关闭
        productListDialog?.setOnCancelListener {
            // 点击外部关闭
        }
    }

    private fun showSearchDialog() {
        if (searchDialog == null) {
            searchDialog = BottomSheetDialog(requireActivity())
            val searchView =
                LayoutInflater.from(requireActivity()).inflate(R.layout.dialog_product_search, null)

            // 设置搜索弹出框的高度与商品弹出框一致
            val displayMetrics = resources.displayMetrics
            val screenHeight = displayMetrics.heightPixels
            val dialogHeight = (screenHeight * 0.7).toInt() // 设置为屏幕高度的70%

            val layoutParams = ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, dialogHeight
            )
            searchView.layoutParams = layoutParams

            searchDialog?.setContentView(searchView)

            // 设置弹窗属性
            searchDialog?.setCancelable(true)
            searchDialog?.setCanceledOnTouchOutside(true)

            // 获取搜索输入框
            val etSearch = searchView.findViewById<EditText>(R.id.et_search)

            etSearch.setOnEditorActionListener { v, actionId, _ ->
                if (actionId == EditorInfo.IME_ACTION_SEND) {
                    val text = etSearch.text?.toString()?.trim().orEmpty()
                    viewMode.liveProductsPageQuery(
                        pageSize, currentPage, mliveData?.id.toString() ?: "", "", text
                    )
                    true

                } else {
                    false
                }
            }
            val tvResultCount = searchView.findViewById<TextView>(R.id.tv_result_count)
            val rvProduct = searchView.findViewById<RecyclerView>(R.id.rvProduct)
            val tvEmpty = searchView.findViewById<TextView>(R.id.tvEmpty)
            val ivBack = searchView.findViewById<ImageView>(R.id.ivBack)

            // 设置RecyclerView
            rvProduct.layoutManager = LinearLayoutManager(requireActivity())
            val searchAdapter = ProductListAdapter(mutableListOf(), true) { product, action ->
                // 处理搜索结果中的商品操作
                when (action) {
                    "view_product" -> {
                        // 显示商品详情
                        ToastUtil.toastShortMessage("查看商品")
                    }
                }
            }
            rvProduct.adapter = searchAdapter

            // 观察搜索结果
            viewMode.liveProductBeanLV.observe(this) { result ->
                if (result?.rows != null && result.rows.isNotEmpty()) {
                    val productList = result.rows
                    searchAdapter.updateProducts(productList)
                    tvResultCount.text = "搜到${result.total}条相关数据"
                    rvProduct.visibility = View.VISIBLE
                    tvEmpty.visibility = View.GONE
                } else {
                    searchAdapter.updateProducts(emptyList())
                    tvResultCount.text = "搜到0条相关数据"
                    rvProduct.visibility = View.GONE
                    tvEmpty.visibility = View.VISIBLE
                }
            }

            // 搜索按钮
            searchView.findViewById<ImageView>(R.id.iv_search).setOnClickListener {
                val keyword = etSearch.text.toString().trim()
                if (keyword.isNotEmpty()) {
                    // 执行搜索
                    viewMode.liveProductsPageQuery(
                        pageSize, currentPage, mliveData?.id.toString() ?: "", "", keyword
                    )
                } else {
                    ToastUtil.toastShortMessage("请输入搜索关键词")
                }
            }

            // 返回按钮
            ivBack.setOnClickListener {
                searchDialog?.dismiss()
            }

            // 设置点击外部关闭
            searchDialog?.setOnCancelListener {
                // 点击外部关闭
            }
        }

        searchDialog?.show()
    }

    private fun setupPager(adapterRebuild: Boolean = false) {
        val vp = viewPager ?: return
        // 简化：不再使用ViewPager承载课件，始终使用 drawing_view，并把课件页作为背景
        vp.visibility = View.GONE
        _binding.drawingView.visibility = View.VISIBLE

        // 仅使用页码与背景切换
        val total = (coursewarePages.size + 1).coerceAtLeast(1)
        val current = (currentPageIndex).coerceIn(0, total - 1)
        showPage(current)
    }

    private fun setupPagingControls() {
        btnPrev?.setOnClickListener {
            if (currentPageIndex > 0) {
                showPage(currentPageIndex - 1)
            }
        }
        btnNext?.setOnClickListener {
            val total = coursewarePages.size + 1
            if (currentPageIndex < total - 1) {
                showPage(currentPageIndex + 1)
            }
        }
    }

    private fun updatePageInfo(current: Int, total: Int) {
        pageInfoView?.text = "$current/$total"
    }

    private fun showPage(index: Int) {
        currentPageIndex = index
        val total = coursewarePages.size + 1
        if (index == 0) {
            // 显示白板
            _binding.drawingView.visibility = View.VISIBLE
            // 清空背景与笔迹
            _binding.drawingView.background = null
            _binding.drawingView.clearAll()
            updatePageInfo(1, total)
        } else {
            // 显示课件作为白板背景
            _binding.drawingView.visibility = View.VISIBLE
            val pageIdx = (index - 1).coerceIn(0, coursewarePages.size - 1)
            val url = coursewarePages[pageIdx].toString()
            // 切换页时清空笔迹
            _binding.drawingView.clearAll()
            // 加载背景图
            Glide.with(requireContext()).asBitmap().load(url).into(object : CustomTarget<Bitmap>() {
                override fun onResourceReady(
                    resource: Bitmap, transition: Transition<in Bitmap>?
                ) {
                    _binding.drawingView.background = BitmapDrawable(resources, resource)
                }

                override fun onLoadCleared(placeholder: Drawable?) {
                    // no-op
                }
            })
            updatePageInfo(index, total)
        }
    }

    @SuppressLint("UseCompatLoadingForDrawables")
    private fun showBottomSheet() {
        viewMode.getCoursewareInfo()

        if (bottomSheetDialog == null) {


            bottomSheetDialog = BottomSheetDialog(requireActivity())
            val bottomSheetView = layoutInflater.inflate(R.layout.bottom_more, null)
            bottomSheetDialog?.setContentView(bottomSheetView)

            // 设置弹窗属性
            bottomSheetDialog?.setCancelable(true)
            bottomSheetDialog?.setCanceledOnTouchOutside(true)


            // 摄像头前后切换按钮
            val tvFront = bottomSheetDialog?.findViewById<TextView>(R.id.tvFront)
            val tvAfter = bottomSheetDialog?.findViewById<TextView>(R.id.tvAfter)

            // 默认选中前置摄像头
            tvFront?.background = requireActivity().getDrawable(R.drawable.view_select_on)
            tvFront?.setTextColor(requireActivity().getColor(R.color.white))
            tvAfter?.background = requireActivity().getDrawable(R.drawable.view_select_off)
            tvAfter?.setTextColor(requireActivity().getColor(R.color.gray))

            tvFront?.setOnClickListener {
                // 选中前摄像头
                tvFront.background = requireActivity().getDrawable(R.drawable.view_select_on)
                tvFront.setTextColor(requireActivity().getColor(R.color.white))
                tvAfter?.background = requireActivity().getDrawable(R.drawable.view_select_off)
                tvAfter?.setTextColor(requireActivity().getColor(R.color.gray))
                (requireActivity() as? ThreePaneLiveActivity)?.switchCamera("1")
                ToastUtil.toastShortMessage("切换到前置摄像头")
            }

            tvAfter?.setOnClickListener {
                // 选中后摄像头
                tvAfter?.background = requireActivity().getDrawable(R.drawable.view_select_on)
                tvAfter?.setTextColor(requireActivity().getColor(R.color.white))
                tvFront?.background = requireActivity().getDrawable(R.drawable.view_select_off)
                tvFront?.setTextColor(requireActivity().getColor(R.color.gray))
                (requireActivity() as? ThreePaneLiveActivity)?.switchCamera("0")
                ToastUtil.toastShortMessage("切换到后置摄像头")

            }

            // 准备数据
            val bottomButtonItems = listOf(
                BottomButtonItem(1, R.mipmap.note_tips_icon, "公告"),
                BottomButtonItem(2, R.drawable.courseware_icon, "课件"),
                BottomButtonItem(3, R.drawable.paying_icon, "播放"),
                BottomButtonItem(4, R.mipmap.coupon_icon, "优惠券"),
                BottomButtonItem(5, R.mipmap.prize_draw_icon, "抽奖"),
                BottomButtonItem(6, R.mipmap.gift_icon, "礼物特效")
            )
// 设置适配器
            val bottomButtonAdapter = BottomButtonAdapter(bottomButtonItems) { item ->
                when (item.id) {
                    1 -> { /* 处理公告点击 */

                        BottomSheetUtils.showAnnouncementBottomSheet(requireActivity()) { content ->
                            // 这里可以处理发布后的逻辑
                            viewMode.pushLiveNotice("", content, mliveData?.id.toString())

                        }
                    }

                    2 -> { /* 处理课件点击 */
                        showCoursewareDialogWithData(
                            context = requireActivity(),
                            coursewareList = coursewareList,
                            onFileSelectedListener = { fileName ->
                                // 处理文件选择
                                val contents = fileName.conversionContent
                                val hasPages = contents.isNotEmpty()
                                _binding.bottomPageControls.visibility =
                                    if (hasPages) View.VISIBLE else View.GONE

                                coursewarePages.clear()
                                coursewarePages.addAll(contents)
                                currentPageIndex = 0
                                setupPager(adapterRebuild = true)
                                showPage(0)

                            },
                            onAddFileClick = { mimeTypes: Array<String> ->
                                // 启动系统文件选择器
                                openDocumentLauncher.launch(mimeTypes)
                            },
                            {
                                _binding.bottomPageControls.visibility = View.GONE
                                coursewarePages.clear()
                                currentPageIndex = 0
                                // 重置白板背景与笔迹
                                _binding.drawingView.background = null
                                _binding.drawingView.clearAll()
                                updatePageInfo(1, 1)
                            })
                    }

                    3 -> { /* 处理插播点击 */
                        showLocalPlayDialog(requireActivity(), mliveData?.interstitialVideoUrl)

                    }

                    4 -> { /* 处理优惠券点击 */


                        val intent = Intent(requireActivity(), CouponActivity::class.java)
                        intent.putExtra("roomId", mliveData?.id.toString())

                        startActivity(intent)
                        bottomSheetDialog?.dismiss()
                    }

                    5 -> { /* 处理优惠券点击 */
                        val intent = Intent(requireActivity(), LotteryActivity::class.java)
                        intent.putExtra("roomId", mliveData?.id.toString())
                        startActivity(intent)
                        bottomSheetDialog?.dismiss()
                    }

                    6 -> { /* 礼物特效 */
                        // 暂停摄像头以避免导航时的错误

                        val intent = Intent(requireActivity(), GiftEffectActivity::class.java)
                        intent.putExtra("roomId", mliveData?.id.toString())
                        startActivity(intent)
                        bottomSheetDialog?.dismiss()

                    }
                }
            }
            bottomSheetView.findViewById<RecyclerView>(R.id.bottomButtonsRecyclerView).apply {
                adapter = bottomButtonAdapter
                val layoutManager2 = GridLayoutManager(context, 4) // 4列
                layoutManager = layoutManager2
            }


            // 设置底部弹窗的控件监听
            setupBottomSheetListeners(bottomSheetView)
        }

        bottomSheetDialog?.show()
    }

    private fun setupBottomSheetListeners(view: View) {

    }

    /**
     * 设置选中的工具按钮
     */
    private fun setSelectedTool(selectedTool: ImageView?) {
        // 清除之前选中工具的背景
        currentSelectedTool?.background = null

        // 设置新选中工具的背景
        selectedTool?.background = requireContext().getDrawable(R.drawable.tool_button_selected)

        // 更新当前选中的工具
        currentSelectedTool = selectedTool
    }


    /**
     * 设置推流监听器
     */
    private fun setupPushListener() {
        mAlivcLivePusher.setLivePushInfoListener(object : AlivcLivePushInfoListener() {
            override fun onPreviewStarted(pusher: AlivcLivePusher?) {
                Log.d("WhiteboardFragment", "录屏预览开始")
            }

            override fun onPreviewStopped(pusher: AlivcLivePusher?) {
                Log.d("WhiteboardFragment", "录屏预览停止")
            }

            override fun onPushStarted(pusher: AlivcLivePusher?) {
                Log.d("WhiteboardFragment", "录屏推流开始")
                requireActivity().runOnUiThread {
                    isScreenStreaming = true
                }
            }

            override fun onPushStopped(pusher: AlivcLivePusher?) {
                Log.d("WhiteboardFragment", "录屏推流停止")
                isScreenStreaming = false
                requireActivity().runOnUiThread {

                    _binding.btnStartLive.text = "开始推流"
                }
            }

            override fun onPushPaused(pusher: AlivcLivePusher?) {
                Log.d("WhiteboardFragment", "录屏推流暂停")
            }

            override fun onPushResumed(pusher: AlivcLivePusher?) {
                Log.d("WhiteboardFragment", "录屏推流恢复")
            }

            override fun onFirstFramePreviewed(pusher: AlivcLivePusher?) {
                Log.d("WhiteboardFragment", "录屏首帧预览")
            }

            override fun onFirstFramePushed(pusher: AlivcLivePusher?) {
            }

            override fun onDropFrame(
                pusher: AlivcLivePusher?, beforeCount: Int, afterCount: Int
            ) {
            }

            override fun onAdjustBitrate(
                pusher: AlivcLivePusher?, currentBitrate: Int, targetBitrate: Int
            ) {
            }

            override fun onAdjustFps(
                pusher: AlivcLivePusher?, currentFps: Int, targetFps: Int
            ) {
            }

            override fun onPushStatistics(
                pusher: AlivcLivePusher?, statistics: AlivcLivePushStatsInfo?
            ) {
            }

            override fun onPushRestarted(pusher: AlivcLivePusher?) {
                Log.d("WhiteboardFragment", "录屏推流重启")
            }
        })
    }


    fun updateProductCounts() {
        // 获取售卖中商品数量
        Log.d("xxxx", "1111111")
        viewMode.getOnSaleProductCount(mliveData?.id.toString() ?: "")
        viewMode.OnSaleProductCountLV.observe(this) { onSaleCount ->
            Log.d("xxxx", "售卖中商品数量: $onSaleCount")
            if (::tabOnSale.isInitialized) {
                tabOnSale.text = "售卖中 ($onSaleCount)"
            }

        }
        // 获取已下架商品数量
        viewMode.getOffShelfProductCount(mliveData?.id.toString() ?: "")
        viewMode.OffShelfProductCountLV.observe(this) { offShelfCount ->
            Log.d("xxxx", "已下架商品数量: $offShelfCount")
            if (::tabOnSale.isInitialized) {
                tabOffShelf.text = "售卖中 ($offShelfCount)"

            }
        }
    }

    /**
     * 开始录屏推流
     */
    private fun startScreenCapturePush() {
        if (isScreenStreaming) {
            // 停止推流
            stopScreenCapturePush()
            return
        }



        try {
            Log.d("WhiteboardFragment", "开始录屏推流，推流地址: ${mliveData?.pushLiveUrl}")
            mAlivcLivePusher.pauseScreenCapture()
            // 配置录屏权限数据到推流配置中
            mAlivcLivePushConfig.mediaProjectionPermissionResultData = mediaProjectionData

            // 开始推流 推到副流上去（录屏模式）
            mAlivcLivePusher.startPush(mliveData?.pushLive3PUrl)

        } catch (e: Exception) {
            Log.e("WhiteboardFragment", "录屏推流失败", e)
            Toast.makeText(requireContext(), "录屏推流失败: ${e.message}", Toast.LENGTH_LONG).show()
        }
    }


    /**
     * 停止录屏推流
     */
    private fun stopScreenCapturePush() {
        try {
            mAlivcLivePusher.stopPush()
            Log.d("WhiteboardFragment", "停止录屏推流")
        } catch (e: Exception) {
            Log.e("WhiteboardFragment", "停止录屏推流失败", e)
            Toast.makeText(requireContext(), "停止推流失败: ${e.message}", Toast.LENGTH_SHORT)
                .show()
        }
    }

    override fun onResume() {
        super.onResume()
        // 从其他Activity返回时恢复摄像头
        (requireActivity() as? ThreePaneLiveActivity)?.resumeCameraFromNavigation()
    }

    override fun onDestroy() {
        super.onDestroy()
        if (isScreenStreaming) {
            stopScreenCapturePush()
        }
        mAlivcLivePusher.destroy()
    }



    companion object {
        private const val ARG_LIVE_DATA = "liveData"
        fun newInstance(mliveData: LiveBean?): WhiteboardFragment {
            val f = WhiteboardFragment()
            val b = Bundle()
            b.putSerializable(ARG_LIVE_DATA, mliveData)
            f.arguments = b
            return f
        }
    }
}